<!DOCTYPE html>
<html lang="en"
      xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>

<head>
    <meta charset="UTF-8">
    <title th:text="#{filePage.title}"></title>
<!--    <link rel="stylesheet" th:href="@{/assets/css/page.css}">-->
    <script th:inline="javascript" >
        const FILE_TYPE_FILE = 0
        const FILE_TYPE_FOLDER = 1
        var _gridWidth;
        var _gridHeight;
        //页面自适应
        function resizePageSize(){
            _gridWidth = $(document).width()-12;
            _gridHeight = $(document).height() - 65 - 40;
        }
        $(function () {
            resizePageSize();
            var _columnWidth = _gridWidth / 4;
            $("#flexigrid-id").flexigrid({
                width: _gridWidth,
                height: _gridHeight,
                url: /*[[@{/file/queryFileInfoListByPage}]]*/"",
                dataType: 'json',
                colModel: [
                    {
                        display: 'fileUuid',
                        name: 'fileUuid',
                        width: 150,
                        sortable: false,
                        align: 'center',
                        hide: 'true'
                    },
                    {
                        display:  /*[[#{file.name}]]*/"",
                        name: 'fileName',
                        width: _columnWidth,
                        sortable: true,
                        align: 'center',
                        process: function (v, trid, _row) {
                            var html = `<div style="display: flex; width: 100px;">`
                                if(_row.fileType === FILE_TYPE_FOLDER){
                                     html += `<a href="#" style="color: rgba(255,131,33,0.6)" class="btn" onclick="enterDir('${_row.fileUuid}','${_row.filePath}')" >
                                                    <i class="glyphicon glyphicon-folder-close" style="margin-right: 5px">
                                                    <span>${v}</span></i>
                                                </a>`
                                }else{
                                    html += `<a href="#" style="color:#46b8da " class="btn" >
                                                    <i class="glyphicon glyphicon-file" style="margin-right: 5px">
                                                    <span>${v}</span></i>
                                              </a>`
                                }
                            html += `</div>`
                            return html;

                        }
                    },
                    {
                        display:  /*[[#{file.fileCapacity}]]*/"",
                        name: 'fileCapacity',
                        width: _columnWidth,
                        sortable: true,
                        align: 'center'
                    },
                    {
                        display:  /*[[#{file.MODTIME}]]*/"",
                        name: 'modtime',
                        width: _columnWidth,
                        sortable: true,
                        align: 'center'
                    },
                    {
                        display:  /*[[#{common.operation}]]*/"",
                        name: 'fileUuid',
                        width: _columnWidth,
                        sortable: true,
                        align: 'center',
                        process: function (v, trid, _row) {
                            var html = `<div>`
                                html += `<a href="#" class="btn" onclick="modifyRoleInfo('${v}')" title=[[#{commom.modify}]]><i class="glyphicon glyphicon-pencil"></i></a>`

                                html += `<a href="#" class="btn" onclick="deleteFile('${v}','${_row.roleName}')" title=[[#{commom.delete}]]><i class="glyphicon glyphicon-trash"></i></a>`

                                html += `<a href="#" class="btn" onclick="copyFile('${v}')" title=[[#{file.copy}]]><i class="glyphicon glyphicon-duplicate"></i></a>`

                                html += `<a href="#" class="btn" onclick="allocatePermission('${v}')" title=[[#{role.allocate.permission}]]><i class="glyphicon glyphicon-share"></i></a>`

                            html += `<div>`
                            return html;

                        }
                    },
                ],
                resizable: false, //resizable table是否可伸缩deleteRoleInfo
                useRp: true,
                usepager: true, //是否分页
                autoload: false, //自动加载，即第一次发起ajax请求
                hideOnSubmit: true, //是否在回调时显示遮盖
                showcheckbox: true, //是否显示多选框
                rowhandler : rowDbclick,
                rowbinddata: true
            });

            query()
            $("#mkdir-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{file.mkdir.dialog.tip}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            var parentId=$("#file-folder-id").attr("parent-id");
                            var flag=$("#file-folder-name-id").checkDom();
                            if (!flag){
                                return
                            }
                            var folderName=$("#file-folder-name-id").val();
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType: 'json',
                                url: /*[[@{/file/mkdirFileInfo}]]*/'',
                                data: [
                                    {name:"parentId",value:parentId},
                                    {name:"folderName",value:folderName}
                                ],
                                success: function (data) {
                                    message(data.msg)
                                    query()
                                    $("#file-folder-name-id").val('');
                                    $("#mkdir-dialog-id").dialog('close')
                                },
                                error: function (msg) {
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function () {
                            $(this).dialog("close");
                        }
                    },
                ]
            })

            /**
             * 修改文件对话框
             */
            $("#modify-file-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{file.modify.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            var flag = $("form#modify-file-form-id input.form-control").checkDom()
                            if (!flag) {
                                return
                            }
                            $("#modify-file-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function () {
                            $(this).dialog("close");
                        }
                    }//end buttons
                ]
            })//end dialog



        })//end function


        //表格查询
        function query() {

            var parentId = $("#file-folder-id").attr("parent-id");
            $("#flexigrid-id").flexOptions({
                extParam:[
                    {name:"parentId",value: parentId}
                ]
            }).flexReload()
        }

        //进入文件夹
        function enterDir(fileUuid,filePath) {
            // alert("进入文件夹" + fileUuid)
            $("#file-folder-id").attr("parent-id",fileUuid)
            if (fileUuid==-1){
                $("#file-folder-id").val("/");
            }
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/queryFileInfoById}]]*/'',
                data: [
                    {name:"fileUuid",value:fileUuid}
                ],
                success: function (data) {
                    if(data){
                        $("#file-folder-id").val(data['filePath']);

                    }
                    else{
                        $("#file-folder-id").val(data["/"]);
                    }
                },
                error: function (msg) {
                    message(/*[[#{common.error}]]*/'');
                }
            });

            query()
        }

        //进入上级文件夹
        function upDir() {
            var fileUuid = $("#file-folder-id").attr("parent-id");
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/queryFileInfoById}]]*/'',
                data: [
                    {name:"fileUuid",value:fileUuid}
                ],
                success: function (data) {
                    if(data){
                        enterDir(data['parentUuid'])
                    }
                    else{
                        $("#file-folder-id").val(data["/"]);
                    }
                },
                error: function (msg) {
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }



        //双击事件
        function rowDbclick(r) {
            $(r).dblclick(
                function () {
                    var columnsArray = $(r).attr('ch').split("_FG$SP_");
                    // console.info(columnsArray);
                    $("#modify-file-dialog-id").dialog('open')

                    var fileUuid = columnsArray[0]

                    modifyFileInfo(fileUuid);
                });
        }


        /**
         * 修改文件信息
         * @param fileUuid
         */
        function modifyFileInfo(fileUuid) {
            $.ajax({
                    type: 'post',
                    async: false,
                    dataType: 'json',
                    url: /*[[@{/file/queryFileInfoById}]]*/'',
                    data: [{name: "fileUuid", value: fileUuid}],
                    success: function (data) {

                        var list = $("form#modify-file-form-id input.form-control");
                        list.each(function (index, item) {
                            var name = $(item).attr("name")
                            $(this).val(data[name])

                        })
                        $("form#modify-file-form-id input.form-control").checkDom()

                        $("#modify-file-dialog-id").dialog('open')
                    },
                    error: function (msg) {
                        message(/*[[#{common.error}]]*/'');
                    }
                }
            );
        }


            // 显示上传弹窗
        function showUploadModal() {
            // 检查弹窗元素是否存在
            const modal = document.getElementById('uploadModal');
            if (modal) {
                // 创建遮罩层
                const overlay = document.createElement('div');
                overlay.id = 'uploadOverlay';
                overlay.style.position = 'fixed';
                overlay.style.top = '0';
                overlay.style.left = '0';
                overlay.style.width = '100%';
                overlay.style.height = '100%';
                overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
                overlay.style.zIndex = '9998';
                document.body.appendChild(overlay);
                
                // 显示弹窗
                modal.style.display = 'block';
                
                // 点击遮罩层关闭弹窗
                overlay.onclick = function() {
                    hideUploadModal();
                };
            } else {
                console.error('上传弹窗元素不存在');
                alert('上传功能加载失败，请刷新页面重试');
            }
        }
        // 隐藏上传弹窗
        function hideUploadModal() {
            // 检查弹窗元素是否存在
            const modal = document.getElementById('uploadModal');
            if (modal) {
                modal.style.display = 'none';
            }
            
            // 移除遮罩层
            const overlay = document.getElementById('uploadOverlay');
            if (overlay) {
                document.body.removeChild(overlay);
            }
            
            // 重置进度条
            try {
                $('#progressBar').width('0%');
                $('#progressBar').text('0%');
            } catch (e) {
                console.error('重置进度条失败:', e);
            }
            
            // 重置表单
            try {
                const form = document.getElementById('uploadForm');
                if (form) {
                    form.reset();
                }
            } catch (e) {
                console.error('重置表单失败:', e);
            }
        }

        $(function () {
            // 初始化上传表单
            $('#uploadForm').submit(function(e) {
                e.preventDefault();
                var formData = new FormData(this);

                // 添加目标目录参数
                formData.append('targetDir', $('#targetDir').val());
                $.ajax({
                    url: /*[[@{/file/upload}]]*/'',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    xhr: function () {
                        var xhr = new XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                var percent = (e.loaded / e.total) * 100;
                                $('#progressBar').width(percent + '%');
                                $('#progressBar').text(percent.toFixed(1) + '%');
                            }
                        });
                        return xhr;
                    },
                    success: function(response) {
                        alert('上传成功');
                        hideUploadModal();
                        window.location.reload();
                    },
                    error: function() {
                        alert('上传失败');
                    }
                });
            });
        });//end ready function

                function syncFileData() {
                    $.ajax({
                        type: 'post',
                        async: false,
                        dataType: 'json',
                        url: /*[[@{/file/syncFileData}]]*/'',
                        data: [],
                        success: function (data) {
                            message(data.msg)

                        },
                        error: function (msg) {
                            message(/*[[#{common.error}]]*/'');
                        }
                    });
                }

        function mkdirFun() {
            $("#mkdir-dialog-id").dialog('open')
        }

        laydate.render({
            elem: '#file-expire-time',
            type: 'datetime', // 支持选择日期+时间
            format: 'yyyy/MM/dd HH:mm', // 日期格式
            min: laydate.now(), // 最小时间为当前时间
            done: function(value, date) {
                // 选择日期后可做的逻辑，比如校验等
                console.log('选择的截止时间：', value);
            }
            //
        });
        function fileShare() {
            // 初始化分享对话框
            $("#share-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{file.share.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            const shareName = $("#file-share-name-id").val().trim();
                            if (!shareName) {
                                alert(/*[[#{file.share.name.required}]]*/'');  // 提示"请输入分享对象"
                                return;
                            }
                            const fileId = $("#current-file-id").attr("data-id");
                            $.ajax({
                                type: 'post',
                                url: /*[[@{/file/share}]]*/'',
                                data: {
                                    fileId: fileId,
                                    shareName: shareName
                                },
                                dataType: 'json',
                                success: function(data) {
                                    if (data.success) {
                                        alert(/*[[#{file.share.success}]]*/'');  // 提示"分享成功"
                                        $(this).dialog("close");
                                        $("#file-share-name-id").val('');
                                    } else {
                                        alert(data.msg || /*[[#{file.share.failed}]]*/'');
                                    }
                                },
                                error: function() {
                                    alert(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',  // 取消按钮文字（如"取消"）
                        click: function() {
                            $(this).dialog("close");  // 关闭对话框
                            $("#file-share-name-id").val('');  // 清空输入框
                        }
                    }
                ]
            });
            // 打开分享对话框
            $("#share-dialog-id").dialog("open");
        }

        // 删除单个文件
        function deleteFile(fileId, fileName) {
            if (confirm('确定要删除文件 "' + fileName + '" 吗？删除后文件将移动到回收站。')) {
                $.ajax({
                    type: 'post',
                    dataType: 'json',
                    url: /*[[@{/recycle/moveToRecycle}]]*/"",
                    data: {fileId: fileId},
                    success: function (data) {
                        message(data.msg);
                        if (data.success) {
                            $("#flexigrid-id").flexReload();
                        }
                    },
                    error: function () {
                        message(/*[[#{common.error}]]*/'');
                    }
                });
            }
        }

        // 批量删除文件
        function batchDeleteFiles() {
            var checkedRows = $("#flexigrid-id").flexGetCheckedRows();
            if (checkedRows.length === 0) {
                alert('请选择要删除的文件');
                return;
            }

            if (confirm('确定要删除选中的 ' + checkedRows.length + ' 个文件吗？删除后文件将移动到回收站。')) {
                var deleteCount = 0;
                var totalCount = checkedRows.length;

                checkedRows.forEach(function(row) {
                    var fileId = row.fileUuid;
                    $.ajax({
                        type: 'post',
                        dataType: 'json',
                        url: /*[[@{/recycle/moveToRecycle}]]*/"",
                        data: {fileId: fileId},
                        success: function (data) {
                            deleteCount++;
                            if (deleteCount === totalCount) {
                                message('批量删除完成，共删除 ' + totalCount + ' 个文件');
                                $("#flexigrid-id").flexReload();
                            }
                        },
                        error: function () {
                            deleteCount++;
                            if (deleteCount === totalCount) {
                                message('批量删除完成，部分文件删除失败');
                                $("#flexigrid-id").flexReload();
                            }
                        }
                    });
                });
            }
        }


    </script>
</head>
<body>
<header>

    <a href="#" class="btn-info btn" onclick="upDir()" th:title="#{file.up.folder}">
        <i class="glyphicon glyphicon-open"></i>
    </a>
    <input id="file-folder-id" th:placeholder="#{file.name.plc}" value="/" parent-id="-1" >




    <a href="#" class="btn-info btn" onclick="query()">
        <i class="glyphicon glyphicon-search"></i>
        <span th:text="#{common.query}"></span>
    </a>

<!--    <a href="#"  class="btn-info btn" onclick="addRole()">-->
<!--        <i class="glyphicon glyphicon-plus"></i>-->
<!--        <span th:text="#{common.add}"></span>-->
<!--    </a>-->

    <a href="#"  class="btn-info btn" onclick="bathDeleteRole()">
        <i class="glyphicon glyphicon-trash"></i>
        <span th:text="#{common.delete}"></span>
    </a>


    <a href="#" class="btn-info btn" onclick="syncFileData()">
        <i class="glyphicon glyphicon-refresh"></i>
        <span th:text="#{file.sync.data}"></span>
    </a>


<!--    <a href="#" class="btn-info btn" onclick="">-->

    <!--文件上传按钮 -->
    <a href="#" class="btn-info btn" onclick="showUploadModal()">

        <i class="glyphicon glyphicon-upload"></i>
        <span th:text="#{file.upload}"></span>
    </a>


    <!-- 分享按钮 -->
    <a href="#" class="btn-info btn" onclick="fileShare()">
        <i class="glyphicon glyphicon-share"></i>
        <span th:text="#{file.share.permission}"></span>
    </a>
    <!-- 创建文件夹 -->
    <a href="#" class="btn-info btn" onclick="mkdirFun()">
        <i class="glyphicon glyphicon-book"></i>
        <span th:text="#{file.mkdir}"></span>
    </a>

</header>

    <table id="flexigrid-id"></table>

    <div id="mkdir-dialog-id" style="display: none">
        <div class="form-group">
            <span th:text="#{file.folder.name}"></span>
            <input id="file-folder-name-id" class="form-control" pattern="^.+$">
        </div>
    </div>
    <div id="share-dialog-id" style="display: none">
        <div class="form-group">
            <span th:text="#{file.share.name}"></span>
            <!-- 截止时间选择框 -->
            <div class="input-group date" id="expire-date-picker">
                <input type="text" class="form-control" id="file-expire-time" placeholder="选择截止时间" />
                <span class="input-group-addon">
                <i class="glyphicon glyphicon-th"></i>
            </span>
            </div>
        </div>
    </div>
<!-- 分享按钮 -->
<a href="#" class="btn-info btn" onclick="fileShare()">
    <i class="glyphicon glyphicon-share"></i>
    <span th:text="#{file.share.permission}"></span>
</a>
</body>

<!-- 上传弹窗 -->
<div id="uploadModal" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid #ccc; padding: 20px; background: white; z-index: 9999; width: 500px;">
    <h3 th:text="#{upload.title}" style="margin-top: 0;"></h3>
    <div style="margin: 20px 0;">
        <form id="uploadForm" enctype="multipart/form-data">

            <div class="form-group">
                <label th:text="#{upload.files}"></label>
                <input type="file" name="files" multiple directory webkitdirectory mozdirectory>
                <p class="help-block" th:text="#{upload.file.tip}"></p>
            </div>

            <div class="progress">
                <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%">
                </div>
            </div>

            <div style="margin-top: 15px; display: flex; justify-content: flex-end; gap: 10px;">
                <button type="button" class="btn btn-default" onclick="hideUploadModal()" th:text="#{common.cancel}"></button>
                <button type="submit" class="btn btn-primary" th:text="#{upload.submit}"></button>
            </div>
        </form>
    </div>
</div>


<div id="modify-file-dialog-id" >
    <form id="modify-file-form-id" method="post" th:action="@{/file/modifyFileInfoById}">
        <div class="form-group">
            <span th:text="#{file.uuid}"></span>
            <input class="form-control" name="fileUuid" readonly>
        </div>

        <div class="form-group">
            <span th:text="#{file.name}"></span>
            <input class="form-control" name="fileName" pattern="^.{4,}$">
        </div>

        <div class="form-group">
            <span th:text="#{file.filePath}"></span>
            <input class="form-control" name="filePath"
                   pattern="^.*$">
        </div>

        <div class="form-group">
            <span th:text="#{file.fileType}"></span>
            <input class="form-control" name="fileType"
                   pattern="^.*$">
        </div>

        <div class="form-group">
            <span th:text="#{file.fileCapacity}"></span>
            <input class="form-control" name="fileCapacity"
                   pattern="^.*$">
        </div>



    </form>

</div>

</html>